package org.lovo.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    private  static final  long EXPIRE_TIME=1000*60*500; //过期时间毫秒
    private static  final String TOKEN_SECRET="j181";//密锁

    /**
     * 创建token
     * @param map 需要放入token的内容
     * @return token
     */
    public static String createToken(Map<String,String> map) {
        //过期时间
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        //私钥及加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        //设置头信息
        HashMap<String, Object> header = new HashMap<>(2);
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        //附带username和userID生成签名
//        String token= JWT.create().withHeader(header)
//                .withClaim("userName", userName)
//                .withExpiresAt(date).sign(algorithm);
        JWTCreator.Builder builder=JWT.create().withHeader(header);
        for(String key:map.keySet()) {
            builder.withClaim(key, map.get(key));
        }
       return builder.withExpiresAt(date).sign(algorithm);
    }

    /**
     *认证
     * @param token 认真token,数组为token中存在的key
     * @return  key对应的值，如果认证失败返回null
     */
   public static Map<String,String> verifierJwt(String token,String...strings){
       Map<String,String> map=new HashMap<>();
       //私钥及加密算法
       Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
//       String userName="";
       JWTVerifier verifier = JWT.require(algorithm).build();
       try {
           DecodedJWT jwt = verifier.verify(token);
           for(String key:strings) {
             map.put(key,jwt.getClaim(key).asString());
           }
       }catch (Exception e){
           return  null;
       }
       return map;
   }
}
